package com.example.demo.configuration;

import com.example.demo.utils.LoggerConfig;
import com.example.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器
 */
@Component
public class SysInterceptor extends HandlerInterceptorAdapter {

    private final static String TOKEN = "token";

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 默认未登录
        LoggerConfig.getLoggerInfo("spring boot 拦截器");
        if (assertLogin(request, TOKEN)) {
            return true;
        } else {
            LoggerConfig.getLoggerInfo("当前用户未登录");
            try {
                response.sendRedirect(request.getContextPath()+"/login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }


    /**
     * 根据key来判断当前人员是否已经登录
     *
     * @param request 传入
     * @return true表示登录了，false表示未登录
     */
    private boolean assertLogin(HttpServletRequest request, String key) {
        return getIdByCookie(request,key);
    }

    /**
     * 通用cookies查找用户ID
     *
     * @param request 通过cookie获取用户ID
     * @return 返回用户ID
     */
    private boolean getIdByCookie(HttpServletRequest request, String key) {
        if (getCookieByKey(request, key).length() != 0 || getCookieByKey(request, key) != null) {
            key = getCookieByKey(request, key);
            return redisUtil.hasKey(key);
        }else{
            return false;
        }
    }

    /**
     * 获取key对应的值
     * @param request 请求
     * @param key     键值
     * @return 返回对应的值
     */
    private String getCookieByKey(HttpServletRequest request, String key) {
        String value = "";
        try {
            // 首次访问可能不会携带Cookies
            Cookie[] cookies = request.getCookies();
            if (cookies.length != 0){
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(key)) {
                        value = cookie.getValue();
                    }
                }
            }
        }catch (NullPointerException e){
            LoggerConfig.getLoggerWarn("当前登录人没有cookie字段传入");
            return value;
        }
        return value;
    }
}
